package com.hkd.forum.interceptor;

import com.hkd.forum.config.AppConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Value("${bit-forum.login.url}")
    private String defaultURL;

    /**
     * 前置处理（预处理）
     * @param request
     * @param response
     * @param handler
     * @return true ：继续 <br/> false ：流程中断
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession(false);
        //通过
        if(session != null && session.getAttribute(AppConfig.USER_SESSION) != null){
            return true;
        }
        //不通过跳转

        //检测URL
        if(!defaultURL.startsWith("/")){
            defaultURL = "/" + defaultURL;
        }
        response.sendRedirect(defaultURL);//降低耦合将跳转的网址配置到yml中
        return false;
    }
}
